<template>
	<div>
		<div class="p20 bgWhite radius8">
			<div class="flex col-center row-between">
				<div class="fb fs16 mb20 flex col-center cursor" @click="back()">
					<el-icon>
						<ArrowLeftBold />
					</el-icon>
					<span class="ml15">高级筛选</span>
				</div>
				<div>
					<el-button class="searchBtn h32" type="defaultBtn"
						@click="fastSearchList1()">快速搜索</el-button>
					<el-button class="searchBtn h32" type="defaultBtn" @click="setKey()">设置字段</el-button>
					<!-- <el-button class="searchBtn h32" type="defaultBtn">快速搜索</el-button>
					<el-button class="searchBtn h32" type="defaultBtn">设置字段</el-button> -->
				</div>
			</div>
			<div class="mb15" v-for="(item,i) in cate" :key="i">
				<div class="flex col-center fs14">
					<div class="fb w110">
						{{item.dictLabel}}:
					</div>
					<!-- 业务经理 -->
					<div v-if="item.dictValue == 'businessManagerId'">
						<el-select v-model="queryParams.businessManagerId" placeholder="选择人员" size="large"
							style="width: 200px" @change="changeUser">
							<el-option v-for="dict in teamOptions" :key="dict.userId" :label="dict.userName"
								:value="dict.userId" />
						</el-select>
					</div>
					<div v-else-if="item.dictValue == 'localArea'">
						<!-- 所在地区 -->
						<el-cascader v-model="queryParams.localArea" ref="cascader" style="width:200px;" :props="address"
							@change="handleChangeAddress" size="large" clearable>
						</el-cascader>
					</div>
					<!-- 创建人员 -->
					<div v-else-if="item.dictValue == 'createBy'">
						<el-select v-model="queryParams.createBy" placeholder="选择人员" size="large"
							style="width: 200px" @change="changeCreateBy">
							<el-option v-for="dict in teamOptions" :key="dict.userId" :label="dict.userName"
								:value="dict.userId" />
						</el-select>
					</div>
					<!-- 前归属人 -->
					<div v-else-if="item.dictValue == 'frontBusinessManagerId'">
						<el-select v-model="queryParams.frontBusinessManagerId" placeholder="选择人员" size="large"
							style="width: 200px" @change="changeFrontBusiness">
							<el-option v-for="dict in teamOptions" :key="dict.userId" :label="dict.userName"
								:value="dict.userId" />
						</el-select>
					</div>
					<!-- 保护到期时间 -->
					<div v-else-if="item.dictValue == 'protectTime'">
						<el-date-picker
							size="large"	
						  v-model="protectTime"
						  type="datetimerange"
						  range-separator="至"
						  start-placeholder="开始时间"
						  end-placeholder="结束时间"
						  format="YYYY-MM-DD HH:mm:ss"
						  @change="changeDatePicker1"
						/>
					</div>
					<!-- 更新时间 -->
					<div v-else-if="item.dictValue == 'updateTimes'">
						<el-date-picker
						  size="large"	
						  v-model="updateTimes"
						  type="datetimerange"
						  range-separator="至"
						  start-placeholder="开始时间"
						  end-placeholder="结束时间"
						  format="YYYY-MM-DD HH:mm:ss"
						  @change="changeDatePicker2"
						/>
					</div>
					<!-- 创建时间 -->
					<div v-else-if="item.dictValue == 'createTimes'">
						<el-date-picker
						  size="large"	
						  v-model="createTimes"
						  type="datetimerange"
						  range-separator="至"
						  start-placeholder="开始时间"
						  end-placeholder="结束时间"
						  format="YYYY-MM-DD HH:mm:ss"
						  @change="changeDatePicker3"
						/>
					</div>
					<!-- 所属部门 -->
					<div v-else-if="item.dictValue == 'currentDeptId'">
						<el-tree-select
							size="large"
						    v-model="queryParams.currentDeptId"
						    :data="deptOptions"
						    :props="{ value: 'id', label: 'label', children: 'children' }"
						    value-key="id"
						    placeholder="请选择归属小组"
						    check-strictly
							style="width: 200px;"
							@change="changeCreateBy"
						/>
					</div>
					<!-- 前所属部门 -->
					<div v-else-if="item.dictValue == 'frontDeptId'">
						<el-tree-select
							size="large"
						    v-model="queryParams.frontDeptId"
						    :data="deptOptions"
						    :props="{ value: 'id', label: 'label', children: 'children' }"
						    value-key="id"
						    placeholder="请选择归属小组"
						    check-strictly
							style="width: 200px;"
							@change="changeCreateBy"
						/>
					</div>
					<!-- 其他点击选中 -->
					<div v-else style="width: 850px;">
						<span v-for="(items,index) in item.arr" :key="index" class="disInBlock mr20  cursor cate-item"
							:class="[{'main-color bg-color-EDF7F7':items.disabled == true},{'color2':items.disabled == false || !items.disabled}]"
							@click="tabItem(i,index)">
							{{items.label}}
						</span>
					</div>
				</div>
			</div>
			<div class="flex col-center row-between fs14" v-if="tagsArr.length > 0">
				<div class="flex col-center fs14">
					<div class="fb w120">
						已选条件：
					</div>
					<div>
						<span class="disInBlock tags mr10" v-for="(item,k) in tagsArr" :key="k">{{item.label}}</span>
					</div>
				</div>
				<div>
					<!-- dialogAddVisible = true -->
					<span class="main-color cursor mr20" @click="confirmSearch()">确定为快速搜索</span>
					<span class="main-color cursor" @click="clearFilter()">清除全部搜索条件</span>
				</div>
			</div>
		</div>
		<!-- 快速搜索弹窗 -->
		<el-dialog class="dialogs" v-model="dialogSearchVisible" title="快速搜索列表" width="420">
			<template #header="{ close, titleId, titleClass }">
				<div slot="title" class="my-header">
					<div :class="titleClass">
						快速搜索列表
						<div class="color2 fs12">点击名称切换快速搜索</div>
					</div>
				</div>
			</template>
			<el-table v-if="fastList.length > 0" :data="fastList" border style="width: 100%;"
				:header-row-style="{background:'#FAFAFA',color:'#0C1019',height:'54px'}" :cell-style="{height:'54px'}">
				<el-table-column align="center" prop="fastName" label="快速搜索名称">
					<template #default="scope">
						<div class="cursor" @click="fastNameSearch(scope.row)">
							{{scope.row.fastName}}
						</div>
					</template>
				</el-table-column>
				<el-table-column fixed="right" label="操作" align="center" width="200px"
					class-name="small-padding fixed-width" prop="address">
					<template #default="scope">
						<el-button link type="primary" @click="fastEdit(scope.row)">编辑</el-button>
						<el-divider direction="vertical" />
						<el-button link type="primary" @click="fastSearchDel1(scope.row.id)">删除</el-button>
						<el-divider direction="vertical" />
						<el-button link type="primary" 
						@click="!scope.row.topUpTime ?  fastTopUp1(scope.row.id) : cancelTopUp(scope.row.id)">
							{{!scope.row.topUpTime ? '置顶' : '取消置顶'}}
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-empty v-else description="暂无数据" />
		</el-dialog>
		<!-- 设置字段 -->
		<el-dialog class="dialogs" v-model="dialogKeyVisible" title="设置筛选字段" width="420">
			<template #header="{ close, titleId, titleClass }">
				<div slot="title" class="my-header">
					<div :class="titleClass">
						设置筛选字段
						<div class="color2 fs12">筛选字段不得少于5项，最多支持7个筛选字段</div>
					</div>
				</div>
			</template>
			<el-table :data="tableData" border style="width: 100%;" height="400"
				:header-row-style="{background:'#FAFAFA',color:'#0C1019',height:'54px'}" 
				:cell-style="{height:'54px'}" @selection-change="handleSelectionChange"
				ref="tableRef"
				row-key="id"
				>
				<el-table-column type="selection" width="55" align="center" />
				<!-- <el-table-column type="selection" width="55" align="center">
					<template #default="scope">
						<el-checkbox v-model="scope.row.checked"></el-checkbox>
				      </template>
				</el-table-column> -->	  
				<el-table-column label="搜索项">
					<template #default="scope">
						{{scope.row.dictLabel}}
					</template>
				</el-table-column>
				<el-table-column fixed="right" label="拖动调整顺序" align="center" width="100px"
					class-name="small-padding fixed-width" prop="address" 
					@mousedown="dragHandle.dragStart(row, $index)"
					>

					<template #default="scope" >
						<el-button link type="primary">拖动排序</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div slot="footer" class="dialog-footer flex col-center row-between mt30">
				<span class="main-color cursor" @click="resetDefaultKey()">恢复默认</span>
				<div>
					<el-button class="cancelSubBtn" @click="dialogKeyVisible = false">取 消</el-button>
					<el-button type="primary" @click="setFieldSave1" class="mainSubBtn">确 定</el-button>
				</div>
			</div>
		</el-dialog>
		<!-- 保存为快速搜索 -->
		<el-dialog v-model="dialogAddVisible" center title="新建快速搜索" width="420">
			<el-form :model="form" ref="formRef" :rules="rules" label-width="120px">
				<el-form-item label="设置名称" prop="name">
					<el-input v-model="form.name" size="large"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer text-right mt30">
				<el-button class="cancelSubBtn" @click="dialogAddVisible = false">取 消</el-button>
				<el-button type="primary" @click="addSearchSubmit" class="mainSubBtn">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script setup name="CustomerItem">
	import {
		fastSearchList,
		fastTopUp,//置顶
		cancelFastTopUp,//取消置顶
		fastSearchDel,
		defaultKey,
		fastSearchSave,//设置筛选字段
		setFieldSave,//添加和编辑字段
		setFieldList,//获取我选择的字段
	} from "@/api/business/customer";
	import {
	   getDivisions
	} from "@/api/business/opportunity.js";
	import {
	   deptTreeSelect
	} from "@/api/business/deptOpportunity.js";
	import {
		defineEmits,
		ref
	} from 'vue'
	import { ElMessage } from 'element-plus'
	const emit = defineEmits(['queryParamsFunc']) // 定义事件
	import {
		defineProps
	} from 'vue'
	import Sortable from "sortablejs"
	const {
		proxy
	} = getCurrentInstance();
	const {
		bus_client_tag,
		bus_customer_type,
		bus_customer_status,
		bus_channel,
		bus_customer_starlevel,
		bus_source,//客户来源
	} = proxy.useDict("bus_client_tag","bus_customer_type","bus_customer_status","bus_channel", "bus_customer_starlevel", "bus_source");
	// const teamOptions = ref([])
	const props = defineProps({
		queryParamsProp: {
			type: Object,
			default: {}
		},
		activeName:{
			type: String,
			default: 1
		},
		// propBus: {
		// 	type: Object,
		// 	default: {}
		// },
		teamOptions: {
			type: Array,
			default: []
		},
	})
	const dialogSearchVisible = ref(false) //快速搜素
	const tableData = ref([])
	const dialogKeyVisible = ref(false) //设置字段
	const dialogAddVisible = ref(false) //添加搜索
	// 重置搜索字段
	function resetQuery(){
		queryParams.value = {
			customerStatus: '', //客户状态
			customerType: '', //客户类型
			customerStarLevel: '', //客户星级
			startTime: '', //开始时间
			endTime: '', //结束时间					
			keyWords: '', //关键词
			customerRoleType: '', //客户分类
			recentlyConsumption: '', //最近消费
			recentlyConsumptionNumber: '', //最近消费次数
			followUpStartTime: '', //下次跟进开始时间
			followUpEndTime: '', //下次跟进结束时间
			customerLabels: '', //客户标签
			businessManagerId: '', //业务经理
			initialName:'',//首字母
			opportunityChannel:'',//客户来源
			localArea:'',//所在地区
			protectTime:'',//保护到期时间
			createBy:'',//创建人员
			currentDeptId:'',//所属部门
			frontBusinessManagerId:'',//前归属人
			frontDeptId:'',//前所属部门
			updateTimes:'',//更新时间
			createTimes:'',//创建时间
		}
	}
	const form = reactive({
		name: ''
	})
	const fastList = ref([])
	// 快速搜索列表
	function fastSearchList1(num) {
		fastSearchList().then(res => {
			fastList.value = res.data
			if(num != 1){
				dialogSearchVisible.value = true
			}
		})
	}
	
	//置顶
	function fastTopUp1(id) {
		fastTopUp(id).then(res => {
			fastSearchList1()
		})
	}
	//取消置顶
	function cancelTopUp(id){
		cancelFastTopUp(id).then(res=>{
			fastSearchList1()
		})
	}
	//删除
	function fastSearchDel1(id) {
		fastSearchDel(id).then(res => {
			fastSearchList1()
		})
	}
	//筛选字段选择
	const chooseKey = ref([])
	function handleSelectionChange(selection) {
		let arr = []
		for(let key in selection){
			let item = {
				fieldCode: selection[key].dictValue,
				fieldName: selection[key].dictLabel
			}
			arr.push(item)
		}
		chooseKey.value = arr
	}
	// 添加和修改字段
	function setFieldSave1(){
		if(chooseKey.value.length < 5){
			ElMessage.error('至少选择5项')
			return false
		}else if(chooseKey.value.length > 7){
			ElMessage.error('最多选择7项')
			return false
		}
		setFieldSave(chooseKey.value).then(res=>{
			// 重新请求我的
			setFieldList1()
			tagsArr.value = []
			dialogKeyVisible.value = false
		})
	}
	const id = ref('')
	const fastContent = ref('')
	//新建快速搜索
	function addSearchSubmit(){
		let arr = []
		let data = {
			fastName:form.name,
			fastContent:id.value == '' ? JSON.stringify(tagsArr.value) : fastContent.value,
			id:id.value
		}
		fastSearchSave(data).then(res=>{
			dialogAddVisible.value = false
			id.value = ''
			fastContent.value = ''
			fastSearchList1(1)
		})
	}
	
	//编辑快速搜索
	function fastEdit(item){
		dialogAddVisible.value = true
		form.name = item.fastName
		id.value = item.id
		fastContent.value = item.fastContent
	}
	// 点击快速搜索名字搜索
	function fastNameSearch(item){
		let query = JSON.parse(item.fastContent)
		resetQuery()
		getCate()
		dialogSearchVisible.value = false
		tagsArr.value = []
		for(let key in query){
			searchKey(query[key].value,query[key].dictValue)
		}
		handleQuery()
	}
	const queryParams = ref(
		{
			businessManagerId:''
		}
	);
	// 地区  省市区
	const address = reactive({
	  checkStrictly: false, // 开启懒加载
	  lazy: true,
	  //可选择任意节点
	  lazyLoad: function (node, resolve) { //node为当前点击的节点，resolve为数据加载完成的回调(必须调用)
	    setTimeout(() => {
	      const nodes = [];
	      // 构造查询条件
	      let query = {
	        id: node.level == 0 ? 0 : node.value,
	        level: node.level + 1,
	        type: 'provinces',
	        pCode: node.value,
	        pageNum: 1,
	        pageSize: 5000
	      }
	      if (query.level == 2) {
	        query.type = 'cities';
	        form.customerAddress = node.label;
	      }
	      if (query.level == 3) {
	        query.type = 'areas';
	      }
	      if (query.level == 4) {
	        query.type = 'streets';
	      }
	      //查询接口
	      getDivisions(query, query.type).then(res => {
	        res.rows.map((item) => {
	          let obj = {
	            value: item.code,
	            label: item.name,
	            pCode: item.pCode,
	            leaf: query.level >= 3
	            //leaf: item.hasChildren // 节点级别，如果没有子节点就停止查询
	          }
	          nodes.push(obj);
	        })
	        //重新加载节点
	        resolve(nodes);
	      })
	    }, 100);
	  }
	})
	//获取选中的名字
	let labels = ref();
	
	function handleChangeAddress(value) {	 
		queryParams.value.localArea = value[value.length - 1];
		// console.log(queryParams.value.localArea,value,'value===')
		handleQuery()
	}
	// 获取我选择的字段
	function setFieldList1(){
		setFieldList().then(res=>{
			cate.value = res.data
			for(let key in cate.value){
				cate.value[key].dictLabel  = cate.value[key].fieldName
				cate.value[key].dictValue  = cate.value[key].fieldCode
			}
			let query = {}
			cate.value.forEach(item => {
			  query[item.dictValue] = ''
			});
			queryParams.value = query
			queryParams.value.pageNum = props.queryParamsProp.pageNum
			queryParams.value.pageSize = props.queryParamsProp.pageSize
			
			for (let key in cate.value) {
				switchCate(cate.value[key].dictValue, key)
			}
			getCate()
		})
	}
	setFieldList1()
	// 确定为快速搜索
	function confirmSearch(){
		dialogAddVisible.value = true
	}
	const cate = ref([])
	// 获取全部字段
	function defaultKey1() {
		defaultKey().then(res => {
			tableData.value = res.data
			for(let key in tableData.value){
				tableData.value[key].id = key
			}
			
		})
	}
	defaultKey1()
	// 点击设置出现弹窗
	const tableRef = ref()
	function setKey(){
		dialogKeyVisible.value = true
		setTimeout(()=>{
			// 设置默认字段,我已经选中的
			for(let j in tableData.value){
				for(let key in cate.value){
					if(tableData.value[j].dictValue == cate.value[key].fieldCode ){
						tableRef.value.toggleRowSelection(tableData.value[j], true) 
					}
				}
			}
			rowDrop()
		},500)
	}
	//恢复默认
	function resetDefaultKey(){
		setTimeout(()=>{
			for(let j in tableData.value){
				tableRef.value.toggleRowSelection(tableData.value[j], false) 
				if(tableData.value[j].dictValue == 'customerRoleType' 
				 || tableData.value[j].dictValue == 'customerType'
				 || tableData.value[j].dictValue == 'customerStatus'
				 || tableData.value[j].dictValue == 'customerStarLevel'
				 || tableData.value[j].dictValue == 'recentlyConsumption'
				 || tableData.value[j].dictValue == 'recentlyConsumptionNumber'
				 || tableData.value[j].dictValue == 'followUpTime'
				 ){
					tableRef.value.toggleRowSelection(tableData.value[j], true) 
				}
			}
		},500)
	}
	// 时间范围-保护到期时间
	const protectTime = ref('')
	function changeDatePicker1(e){
		let arr = [transDate(e[0]),transDate(e[1])]
		queryParams.value.protectTime = arr.join(',')
		handleQuery()
	}
	// 更新时间
	const updateTimes = ref('')
	function changeDatePicker2(e){
		let arr = [transDate(e[0]),transDate(e[1])]
		queryParams.value.updateTimes = arr.join(',')
		handleQuery()
	}
	//创建时间
	const createTimes = ref('')
	function changeDatePicker3(e){
		let arr = [transDate(e[0]),transDate(e[1])]
		queryParams.value.createTimes = arr.join(',')
		handleQuery()
	}
	//所属部门
	const deptOptions = ref(undefined);
	/**
	 * 获取部门数据
	 */
	function getDeptTree() {
	  deptTreeSelect().then(response => {
	    deptOptions.value = response.data;
	  });
	};
	getDeptTree()
	const getCate = () => {
		for (let key in cate.value) {
			if (cate.value[key].arr && cate.value[key].arr[0].label != '全部') {
				cate.value[key].arr.splice(0, 0, {
					id: '',
					label: '全部'
				})
			}
			for (let i in cate.value[key].arr) {
				if(cate.value[key].dictValue == "customerRoleType"){
					if(props.activeName == 1 && cate.value[key].arr[i].label == '我的客户'){
						cate.value[key].arr[i].disabled = true
						tagsArr.value = [
							{
								dictValue: "customerRoleType",
								key: "0",
								label: "我的客户",
								value: 1,
							}
						]
						queryParams.value.customerRoleType = 1
					}else if(props.activeName == 2 && cate.value[key].arr[i].label == '重点客户'){
						cate.value[key].arr[i].disabled = true
						tagsArr.value = [
							{
								dictValue: "customerRoleType",
								key: "0",
								label: "重点客户",
								value: 3,
							}
						]
						queryParams.value.customerRoleType = 3
					}
				}else {
					cate.value[key].arr[i].disabled = false
					cate.value[key].arr[0].disabled = true
				}
			}
		}
	}
	function switchCate(type, key) {
		switch (type) {
			case 'customerRoleType':
				// 客户分类
				cate.value[key].arr = [{
						id: '',
						label: '全部',
					},
					{
						id: 1,
						label: '我的客户',
						value: 1
					},
					{
						id: 2,
						label: '下属客户',
						value: 2
					},
					{
						id: 3,
						label: '重点客户',
						value: 3
					},
					{
						id: 4,
						label: '今日新增',
						value: 4
					}
				]
				
				break;
			case 'customerType':
				//客户类型
				cate.value[key].arr = bus_customer_type
				break;
			case 'customerStatus':
				//客户状态
				cate.value[key].arr = bus_customer_status
				break;
			case 'customerStarLevel':
				//客户星级
				cate.value[key].arr = bus_customer_starlevel
				break;
			case 'recentlyConsumption':
				//最近消费
				cate.value[key].arr = [{
						id: '',
						label: '全部',
						disabled: true
					},
					{
						id: 1,
						label: '1周内',
						value: 1
					},
					{
						id: 2,
						label: '2周内',
						value: 2
					},
					{
						id: 3,
						label: '1月内',
						value: 3
					}
				]
				break;
			case 'recentlyConsumptionNumber':
				//消费次数
				cate.value[key].arr = [{
						id: '',
						label: '全部',
						disabled: true
					},
					{
						id: 1,
						label: '1次',
						value: 1
					},
					{
						id: 2,
						label: '2次',
						value: 2
					},
					{
						id: 3,
						label: '3次',
						value: 3
					},
					{
						id: 4,
						label: '4次',
						value: 4
					},
					{
						id: 5,
						label: '5次',
						value: 5
					},
					{
						id: 6,
						label: '5次以上',
						value: 6
					}
				]
				break;
			case 'followUpTime':
				//下次跟进时间
				cate.value[key].arr = [{
						id: '',
						label: '全部',
						disabled: true
					}, {
						id: 1,
						label: '今天',
						value: 1
					},
					{
						id: 2,
						label: '明天',
						value: 2
					},
					{
						id: 3,
						label: '本周',
						value: 3
					},
					{
						id: 4,
						label: '下周',
						value: 4
					},
					{
						id: 5,
						label: '本月',
						value: 5
					},
					{
						id: 6,
						label: '下月',
						value: 6
					},
					// {id:7,label:'自定义时间段',value:7}
				]
				break;
			case 'customerLabels':
				cate.value[key].arr = bus_client_tag
				break;
			case 'initialName':
				cate.value[key].arr = generateAlphabetList()				
				break;
			case 'opportunityChannel':
			//来源渠道
				cate.value[key].arr = bus_channel
				break;	
			case 'opportunitySource':
			//客户来源
				cate.value[key].arr = bus_source
				break;		
			default:
				break;
		}

	}
	// A-Z
	function generateAlphabetList(){
		let alphabet = [];
		for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) {
			let item = {
					id: i,
					label: String.fromCharCode(i),
					value: String.fromCharCode(i)
				}
		  alphabet.push(item);
		}
		return alphabet
	}
	const rules = {
		name: [{
			required: true,
			message: '请输入名称',
			trigger: 'blur'
		}, ]
	}

	const formRef = ref(null)
	// 返回常规搜索	
	function back() {
		// for (let key in cate.value) {
		// 	cate.value[key].arr.splice(0, 1)
		// }
		resetQuery()
		emit('queryParamsFunc', queryParams)
		emit('back')
	}
	
	const options = [{
			value: '',
			label: '不限',
		},
		{
			value: '1',
			label: '已成交',
		},
		{
			value: '0',
			label: '正在跟进',
		},
	]
	
	
	// 选中的筛选条件
	const tagsArr = ref([])
	
	// 选择业务经理
	function changeUser(e) {
		emit('queryParamsFunc', queryParams) // 触发 'update' 事件，并传递参数
	}
	//选择创建人员
	function changeCreateBy(e){
		emit('queryParamsFunc', queryParams) // 触发 'update' 事件，并传递参数
	}
	//选择归属人员
	function changeFrontBusiness(e){
		emit('queryParamsFunc', queryParams) // 触发 'update' 事件，并传递参数
	}
	const tabItem = (i, index) => {
		// 选中样式
		for (let key in cate.value[i].arr) {
			cate.value[i].arr[key].disabled = false
		}
		cate.value[i].arr[index].disabled = true
		let propKey = cate.value[i].dictValue
		// console.log(propKey,'key')
		let value = cate.value[i].arr[index].value
		searchKey(value,propKey,1)
	}	
	// 点击之后赋值
	function searchKey(value,propKey,type){	
		switch (propKey) {
			case 'customerRoleType':
				// 我的客户
				queryParams.value.customerRoleType = value
				break;
			case 'customerType':
				// 客户类型
				queryParams.value.customerType = value
				break;
			case 'customerStatus':
				// 客户状态
				queryParams.value.customerStatus = value
				break;
			case 'customerStarLevel':
				// 客户星级
				queryParams.value.customerStarLevel = value
				break;
			case 'recentlyConsumption':
				// 最近消费
				queryParams.value.recentlyConsumption = value
				break;
			case 'recentlyConsumptionNumber':
				// 消费次数
				queryParams.value.recentlyConsumptionNumber = value
				break;
			case 'followUpTime':
				// 下次跟进时间
				let getValueNum = value
				if (getValueNum) {
					checkTime(getValueNum)
				} else {
					queryParams.value.startTime = ''
					queryParams.value.endTime = ''
				}
				break;
			case 'customerLabels':
				// 客户标签
				queryParams.value.customerLabels = value
				break;
			case 'initialName':
				// 字母
				queryParams.value.initialName = value
				break;	
			case 'opportunityChannel':
				// 来源渠道
				queryParams.value.opportunityChannel = value
				break;	
			case 'opportunitySource':
			//客户来源
				queryParams.value.opportunitySource = value
				break;			
			default:
				break;
		}
		// ==1点击之后搜索，否则只赋值不搜索
		if(type == 1){
			chooseKeySearch()	
		}
	}	
	// 点击之后赋值搜索
	 function chooseKeySearch(){	
		let arr = []
		for (let key in cate.value) {
			for (let j in cate.value[key].arr) {
				if (cate.value[key].arr[j].id != '' && cate.value[key].arr[j].disabled == true) {
					let item = {
						key: key,
						label: cate.value[key].arr[j].label,//展示文字
						dictValue: cate.value[key].dictValue,//后台存储字段
						value:cate.value[key].arr[j].value,//选中的字段
					}
					arr.push(item)
				}
			}
		}
		console.log(tagsArr.value,'tagsArr.value')
		tagsArr.value = arr
		handleQuery()
	}
   
		
	
	function getTodayStart() {
		const now = new Date();
		const year = now.getFullYear();
		const month = now.getMonth() + 1; // 月份是从0开始的
		const day = now.getDate();
		let arr = [new Date(year, month - 1, day, 0, 0, 0), new Date(year, month - 1, day, 23, 59, 59)]
		return arr; // 月份是从0开始的，所以减1
	}

	function formatDateTime(date) {
		let arr = []
		for (let key in date) {
			arr[key] = (
				date[key].getFullYear() +
				"-" +
				("0" + (date[key].getMonth() + 1)).slice(-2) +
				"-" +
				("0" + date[key].getDate()).slice(-2) +
				" " +
				("0" + date[key].getHours()).slice(-2) +
				":" +
				("0" + date[key].getMinutes()).slice(-2) +
				":" +
				("0" + date[key].getSeconds()).slice(-2)
			)
		}
		return arr
	}
	//处理下次跟进时间
	function checkTime(num) {
		switch (num * 1) {
			case 1:
				const todayStart1 = getTodayRange();
				queryParams.value.startTime = todayStart1.start
				queryParams.value.endTime = todayStart1.end
				break;
			case 2:
				const todayStart2 = getTomorrowRange();
				queryParams.value.startTime = todayStart2.start
				queryParams.value.endTime = todayStart2.end
				break;
			case 3:
				const todayStart3 = getThisWeekRange(1);
				queryParams.value.startTime = todayStart3.start
				queryParams.value.endTime = todayStart3.end
				break
			case 4:
				const todayStart4 = getThisWeekRange(2);
				queryParams.value.startTime = todayStart4.start
				queryParams.value.endTime = todayStart4.end
				break
			case 5:
				const todayStart5 = getThisMonthRange();
				queryParams.value.startTime = todayStart5.start
				queryParams.value.endTime = todayStart5.end
				break
			case 6:
				const todayStart6 = getNextMonthRange();
				queryParams.value.startTime = todayStart6.start
				queryParams.value.endTime = todayStart6.end
				break
				
			default:
				break;
		}
	}

	function msToDate(milliseconds) {
		var date = new Date(milliseconds);
		return date.toISOString().slice(0, 19).replace('T', ' ');
	}
	// 获取今天的时间区间  
	function getTodayRange() {
		var today = new Date();
		var start = transDate(new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0, 0));
		var end = transDate(new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59, 999));
		return {
			start,
			end
		};
	}

	// 获取明天的时间区间  
	function getTomorrowRange() {
		var today = new Date();
		var tomorrow = new Date(today);
		tomorrow.setDate(today.getDate() + 1);
		var start = transDate(new Date(tomorrow.getFullYear(), tomorrow.getMonth(), tomorrow.getDate(), 0, 0, 0, 0));
		var end = transDate(new Date(tomorrow.getFullYear(), tomorrow.getMonth(), tomorrow.getDate(), 23, 59, 59, 999));
		return {
			start,
			end
		};
	}

	// 获取本周的时间区间（假设周一是周的第一天）  
	function getThisWeekRange(num) {
		// 获取当前日期
		const today = new Date();

		// 获取今天是周几（0代表周日，1代表周一，...，6代表周六）
		const dayOfWeek = today.getDay();

		// 计算本周一的日期（如果今天是周一，dayOfWeek会是1，不需要调整；否则需要减去相应的天数）
		const weekStart = new Date(today);
		weekStart.setDate(today.getDate() - dayOfWeek + 1); // +1 是因为getDay()返回的是0-6，我们需要周一为起始点

		// 将时间设置为周一的凌晨00:00:00
		weekStart.setHours(0, 0, 0, 0);

		// 计算本周日的日期（本周一的日期加上6天）
		const weekEnd = new Date(weekStart);
		weekEnd.setDate(weekStart.getDate() + 6);

		// 将时间设置为周日的凌晨23:59:59（但通常我们只需要到周日的00:00:00来表示一天的开始，即下一周的开始之前）
		// 如果你确实需要周日的结束时间（尽管这通常不是必需的），你可以这样做：
		const endOfDay = new Date(weekEnd);
		endOfDay.setHours(23, 59, 59, 999); // 毫秒设置为999以尽可能接近结束时间，但通常只需到00:00:00即可
		if (num == 1) {
			var start = transDate(weekStart)
			var end = transDate(endOfDay)
		} else {
			// 但通常我们只需要周日的00:00:00来表示本周的结束（即下一周的开始）
			weekEnd.setHours(0, 0, 0, 0);

			// 如果你想要下一周的开始时间（即本周日之后的00:00:00），你可以再次增加一天
			const nextWeekStart = new Date(weekEnd);
			nextWeekStart.setDate(weekEnd.getDate() + 1);
			nextWeekStart.setHours(0, 0, 0, 0);
			const nextWeekEnd = new Date(nextWeekStart);
			nextWeekEnd.setDate(nextWeekStart.getDate() + 6);
			const endOfDay1 = new Date(nextWeekEnd);
			endOfDay1.setHours(23, 59, 59, 999);
			var start = transDate(nextWeekStart)
			var end = transDate(endOfDay1)
		}

		return {
			start,
			end
		}

	}
	// 获取本月的时间区间  
	function getThisMonthRange() {
		const today = new Date();
		var start = transDate(new Date(today.getFullYear(), today.getMonth(), 1, 0, 0, 0, 0));
		var end = transDate(new Date(today.getFullYear(), today.getMonth() + 1, 0, 23, 59, 59, 999));
		return {
			start,
			end
		};
	}

	// 获取下月的时间区间  
	function getNextMonthRange() {
		const today = new Date();
		const nextMonth = new Date(today.getFullYear(), today.getMonth() + 1, 1);
		var start = transDate(new Date(nextMonth.getFullYear(), nextMonth.getMonth(), 1, 0, 0, 0, 0));
		var end = transDate(new Date(nextMonth.getFullYear(), nextMonth.getMonth() + 1, 0, 23, 59, 59, 999));
		return {
			start,
			end
		};
	}

	function transDate(dateString) {
		// 给定的日期字符串  
		// const dateString = "Tue Nov 05 2024 23:59:59 GMT+0800 (中国标准时间)";  

		// 使用Date.parse或者new Date()来解析日期字符串（这里直接使用new Date()因为字符串格式被浏览器支持）  
		const date = new Date(dateString);

		// 提取年、月、日、时、分、秒  
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1，并使用padStart填充前导零  
		const day = String(date.getDate()).padStart(2, '0'); // 使用padStart填充前导零  
		const hours = String(date.getHours()).padStart(2, '0'); // 使用padStart填充前导零  
		const minutes = String(date.getMinutes()).padStart(2, '0'); // 使用padStart填充前导零  
		const seconds = String(date.getSeconds()).padStart(2, '0'); // 使用padStart填充前导零  

		// 格式化为“年月日时分秒”  
		const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

		// 输出结果  
		return formattedDate
	}

	// 
	function handleQuery() {
		// props.queryParamsProp,
		emit('queryParamsFunc', queryParams) // 触发 'update' 事件，并传递参数
	}
	// 清除全部搜索条件
	function clearFilter() {
		tagsArr.value = ''
		for (let key in cate.value) {
			for (let i in cate.value[key].arr) {
				cate.value[key].arr[i].disabled = false
				cate.value[key].arr[0].disabled = true
			}
		}
		queryParams.value = {
			customerStatus: '', //客户状态
			customerType: '', //客户类型
			customerStarLevel: '', //客户星级
			startTime: '', //开始时间
			endTime: '', //结束时间					
			keyWords: '', //关键词
			customerRoleType: '', //客户分类
			recentlyConsumption: '', //最近消费
			recentlyConsumptionNumber: '', //最近消费次数
			followUpStartTime: '', //下次跟进开始时间
			followUpEndTime: '', //下次跟进结束时间
			customerLabels: '', //客户标签
			businessManagerId: '', //业务经理
		}
		handleQuery()
	}
	
	// 表格行拖拽
	   function rowDrop() {
	      let tbody = document.querySelector(".el-table__body-wrapper tbody");
	      Sortable.create(tbody, {
	        // or { name: "...", pull: [true, false, 'clone', array], put: [true, false, array] }
	        group: {
	          name: "words",
	          pull: true,
	          put: true,
	        },
	        animation: 150, // ms, number 单位：ms，定义排序动画的时间
	        onAdd: function () {
	          // 拖拽时候添加有新的节点的时候发生该事件
	          // console.log("onAdd.foo:", [evt.item, evt.from]);
	        },
	        onUpdate: function () {
	          // 拖拽更新节点位置发生该事件
	          // console.log("onUpdate.foo:", [evt.item, evt.from]);
	        },
	        onRemove: function (evt) {
	          // 删除拖拽节点的时候促发该事件
	          console.log("onRemove.foo:", [evt.item, evt.from]);
	        },
	        onStart: function (evt) {
	          // 开始拖拽出发该函数
	          console.log("onStart.foo:", [evt.item, evt.from]);
	        },
	        onSort: function (evt) {
	          // 发生排序发生该事件
	          console.log("onUpdate.foo:", [evt.item, evt.from]);
	        },
	        onEnd(evt) {
	          // 结束拖拽
	          console.log("结束表格拖拽", evt);
	          // 如果拖拽结束后顺序发生了变化，则对数据进行修改
	          if (evt.oldIndex !== evt.newIndex) {
	            let currRow = tableData.value.splice(evt.oldIndex, 1)[0];
	            tableData.value.splice(evt.newIndex, 0, currRow);
	            // 将排序后的ID抽离成数组传给后端
	            // let optIDs: string[] = [];
	            // tableData.value.forEach((item) => {
	            //   optIDs.push(item.ID);
	            // });
	            // const params = {
	            //   Params: {
	            //     SpaceID: spaceID.value,
	            //     LaunchID: launchID.value,
	            //     OptIDs: optIDs,
	            //   },
	            //   Options: {
	            //     APIServer: apiServer,
	            //   },
	            // };
	            // // 发送改变顺序的请求
	            // store.commit("doRequest");
	            // spaceService.OrderOptions(params).then((res: any) => {
	            //   store.commit("deResponse");
	            //   if (res.Status === 0) {
	            //     console.log("表格顺序修改成功");
	            //   } else {
	            //     ElMessage({
	            //       showClose: true,
	            //       message: res.ErrorMessage,
	            //       type: "error",
	            //       duration: 10000,
	            //     });
	            //   }
	            // });
	          }
	        },
	      });
	    };
		
</script>

<style>
	.cate-item {
		border-radius: 4px;
		height: 28px;
		line-height: 28px;
		padding: 0 15px;
	}

	.tags {
		border-radius: 3px;
		background: #FFFFFF;
		border: 1px solid #4DACB1;
		line-height: 30px;
		padding: 0 15px;
		color: #4DACB1;
	}
	.dialogs .el-dialog__body{
		padding: 10px 30px 30px;
	}
</style>